package com.example.leetdemo.finash;

public class Solution1504 {

    public int numSubmat(int[][] mat) {
        int sum = 0;
        int[][] dp = new int[mat.length + 1][mat[0].length + 1];
        for (int i = 0; i < mat.length; i++) {
            for (int j = 0; j < mat[i].length; j++) {
                if (mat[i][j] == 1) {
                    dp[i + 1][j + 1] = dp[i + 1][j] + 1;
                    int min = dp[i + 1][j] + 1;
                    for (int k = i + 1; k >= 0; k--) {
                        if (dp[k][j + 1] != 0) {
                            sum += Math.min(min, dp[k][j + 1]);
                            min = Math.min(min, dp[k][j + 1]);
                        } else {
                            break;
                        }
                    }
                }
            }
        }
        return sum;
    }

}
